package org.example.steamshop.controller;

import org.example.steamshop.form.GameForm;
import org.example.steamshop.model.Game;
import org.example.steamshop.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class GameController {
    @Autowired
    private GameService gameService;

    private static final int PAGE_SIZE = 12;

    @GetMapping("/")
    public String home(@RequestParam(defaultValue = "0") int page, Model model) {
        Pageable pageable = PageRequest.of(page, PAGE_SIZE);
        // 使用新的方法名：查询在售游戏
        Page<Game> gamePage = gameService.findOnSaleGames(pageable);
        model.addAttribute("games", gamePage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", gamePage.getTotalPages());
        return "games";
    }

    @GetMapping("/games")
    public String games(@RequestParam(required = false) String keyword,
                        @RequestParam(defaultValue = "0") int page,
                        Model model) {
        Pageable pageable = PageRequest.of(page, PAGE_SIZE);
        Page<Game> gamePage;
        if (keyword != null && !keyword.trim().isEmpty()) {
            // 使用新的方法名：按名称查询在售游戏
            gamePage = gameService.findGamesByName(keyword,pageable);
            model.addAttribute("keyword", keyword);
        } else {
            // 使用新的方法名：查询所有在售游戏
            gamePage = gameService.findOnSaleGames(pageable);
        }
        model.addAttribute("games", gamePage.getContent());
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", gamePage.getTotalPages());
        return "games";
    }

    @GetMapping("/game/{id}")
    public String gameDetails(@PathVariable Long id, Model model) {
        Game game = gameService.findGameById(id);
        if (game == null) {
            return "redirect:/games";
        }
        model.addAttribute("game", game);
        return "game-details";
    }

    @GetMapping("/games/category/{category}")
    public String gamesByCategory(@PathVariable String category,
                                  @RequestParam(defaultValue = "0") int page,
                                  Model model) {
        Pageable pageable = PageRequest.of(page, PAGE_SIZE);
        // 使用新的方法名：按分类查询在售游戏
        Page<Game> gamePage = gameService.findGamesByCategory(category, pageable);
        model.addAttribute("games", gamePage.getContent());
        model.addAttribute("category", category);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", gamePage.getTotalPages());
        return "games";
    }

    @GetMapping("/admin/games")
    public String showAdminGamesList(Model model) {
        // 使用新添加的获取所有游戏的方法
        List<Game> allGames = gameService.findAllGames();
        model.addAttribute("games", allGames);
        return "admin";
    }

    @PostMapping("/admin/games/{id}/status")
    public String updateGameStatus(@PathVariable Long id,
                                   @RequestParam("status") String status,
                                   RedirectAttributes redirectAttributes) {
        // 调用Service层更新状态
        Game updatedGame = gameService.updateGameStatus(id, status);

        if (updatedGame != null) {
            redirectAttributes.addFlashAttribute("message", "游戏状态更新成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "游戏不存在，状态更新失败");
        }

        return "redirect:/admin/games";
    }


    @GetMapping("/admin/games/add")
    public String showAddGameForm(Model model) {
        model.addAttribute("gameForm", new GameForm());
        return "addgame";
    }

    @PostMapping("/admin/games/add")
    public String addGameSubmit(@ModelAttribute GameForm form, RedirectAttributes redirectAttributes) {
        // 检查游戏名称是否已存在
        if (gameService.existsByName(form.getName())) {
            redirectAttributes.addFlashAttribute("error", "游戏名称已存在");
            return "redirect:/admin/games/add?error";
        }

        // 转换为实体对象并保存
        Game game = convertFormToGame(form);
        gameService.addGame(game);

        // 添加成功消息
        redirectAttributes.addFlashAttribute("success", "游戏添加成功！");
        return "redirect:/admin/games";
    }

    private Game convertFormToGame(GameForm form) {
        Game game = new Game();
        game.setName(form.getName());
        game.setPrice(form.getPrice());
        game.setProducer(form.getProducer());
        game.setLaunchDate(form.getLaunchDate());
        game.setCategory(form.getCategory());
        game.setType(form.getType());
        game.setDescription(form.getDescription());
        game.setImageUrl(form.getImageUrl());
        return game;
    }
}



